const { usersModel } = require('./models/usersModel');

const mongoose = require("mongoose")

module.exports.Register = async params => {
    return await usersModel.create(params)
}
module.exports.Login = async params => {
    return await usersModel.find({ userName: params.userName, delete: false })
}
module.exports.isExist = async params => {
    return await usersModel.find(params);
}




module.exports.getUsers = async function ({
    type,
    value,
    pageSize,
    currentPage
}) {
    const data = await usersModel.aggregate([
        {
            $lookup: {
                // 设置关联的集合名称
                from: "orders",
                // 当前集合中做关联的属性名（字段）
                localField: "_id",
                // 被关联集合对应的属性名
                foreignField: "usersId",
                as: "ordersData"
            }
        },
        {
            $match: {
                delete: false,
                [type]: {
                    $regex: value,
                    $options: "$i"
                }
            }
        },

        {
            $skip: (currentPage - 1) * pageSize
        },

        {
            $limit: (pageSize - 0)
        }
    ])

    const total = await usersModel.countDocuments({
        delete: false,
        [type]: {
            $regex: value,
            $options: "$i"
        }
    })
    const pages = Math.ceil(total / pageSize)

    const users = await usersModel.populate(
        data, {
        path: "sellersId"
    }

    )

    return {
        total,
        pages,
        users
    }
}

module.exports.getUsersById = async function getUsersById(params) {
    return await usersModel.aggregate([{
        $lookup: {
            from: "orders",
            localField: "_id",
            foreignField: "usersId",
            as: "ordersData"
        }
    },
    {
        $match: {
            delete: false,
            _id: mongoose.Types.ObjectId(params._id)
        }
    },
    ])
}


module.exports.changeUsersSeller = async function changeUsersSeller(params) {
    return data = await usersModel.updateOne({ userName: params.userName, userAccount: params.userAccount, userPhone: params.userPhone }, { sellersId: params.sellersId })
}